var paramsObj = {}//初始化获取用户信息传参对象
var sceneList = []
layui.config({
    version: '1510164124181'
}).use(['form', 'laydate', 'laypage', 'layer', 'element', 'table'], function () {
    form = layui.form;
    layer = layui.layer;
    $ = layui.jquery;
    table = layui.table;
    laydate = layui.laydate; //日期
    laypage = layui.laypage; //分页
    element = layui.element; //元素操作

    lay('.inputDate').each(function () {
        laydate.render({
            elem: this,
            type: 'date',
            range: true
        });
    })
    lay('.userVisit_time').each(function() {
        laydate.render({
            elem: this,
            type: 'datetime',
            range: true
        });
    })
    inituserdata();
    getSceneList()
});
//选择用户类型,选择用户状态,电话搜索查询用户
function SearchInfo() {
    pageNo = 1;
    inituserdata();
}

function onloadInfo() {
    inituserdata();
}

function getParamsValue() {
    let join_time = $("#join_time").val(); //加入时间
    let follow_time = $("#follow_time").val(); // 关注时间
    let unfollow_time = $("#unfollow_time").val(); // 取消关注时间
    let order_time = $("#order_time").val(); // 下单时间
    let userVisit_time = $("#userVisit_time").val(); // 用户最近访问时间
    paramsObj.names = $("#names").val();
    paramsObj.inputInfo = $("#inputInfo").val();
    paramsObj.startTime = join_time&&join_time.split(" - ")[0];
    paramsObj.endTime = join_time&&join_time.split(" - ")[1];
    paramsObj.startOfficialSubscribeTime = follow_time&&follow_time.split(" - ")[0];
    paramsObj.endOfficialSubscribeTime = follow_time&&follow_time.split(" - ")[1];
    paramsObj.startOfficialUnsubscribeTime = unfollow_time&&unfollow_time.split(" - ")[0];
    paramsObj.endOfficialUnsubscribeTime = unfollow_time&&unfollow_time.split(" - ")[1];
    paramsObj.startCreateOrderTime = order_time&&order_time.split(" - ")[0];
    paramsObj.endCreateOrderTime = order_time&&order_time.split(" - ")[1];
    paramsObj.startRecentJoinTime = userVisit_time&&userVisit_time.split(" - ")[0];
    paramsObj.endRecentJoinTime = userVisit_time&&userVisit_time.split(" - ")[1];
    paramsObj.officialState = $('#selectSubscribeState').find("option:selected").val();// 订阅状态
    paramsObj.officialType = $('#selectSubscribeType').find("option:selected").val();// 订阅类型
    paramsObj.firstJoinType = $('#selectScene').find("option:selected").val();// 订阅类型
    paramsObj.memberPowerId = $('#selectMember').find("option:selected").val();// selectMember
    if (paramsObj.officialState == -1) { paramsObj.officialState = '' }
    if (paramsObj.officialType == -1) { paramsObj.officialType = '' }
    if (paramsObj.memberPowerId == -1) { paramsObj.memberPowerId = '' }
    if (paramsObj.firstJoinType == -1 || paramsObj.firstJoinType == undefined) { paramsObj.firstJoinType = '' }
}

function ExportInfo() {
    let href = `${httpurl}/UserExportExcel?`
    for (let k in paramsObj) {
        href += `${k}=${paramsObj[k]}&`
    }
    href = href.substring(0, href.length - 1)
    console.log(href);
    window.location.href = href
}

// 场景值，根据ID获取
function getSceneIdValue(id) {
    $.ajax({
        url: httpurl + "/getGoinScenesById",
        cache: false,
        data: { id },
        success: (res) => {
            console.log(res);
        }
    })
}

// 获取所有场景值
function getSceneList() {
    $.ajax({
        url: httpurl + "/getGoinScenesPage",
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        cache: false,
        success: (res) => {
            if (res.rtnCode == 200) {
                sceneList = res.data
                let info = '<option value="-1">请选择</option>';
                for (let i = 0; i < sceneList.length; i++) {
                    info += '<option value="' + sceneList[i].id + '">' + sceneList[i].remark + '</option>';
                }
                $("#selectScene").html(info);
            }
        }
    })
}

//查询用户
function inituserdata() {
    getParamsValue()
    $.ajax({
        // url: httpurl + "/FindUserList",
        url: httpurl + "/user/list",
        cache: false,
        data: {
            "page": pageNo,
            "pagesize": pageRecords,
            ...paramsObj
        },
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        success: function (res) {
            let dataHtml = "";
            if (res.rtnCode == 200) {
                let dataList = res.data.list;
                totalRecords = res.data.total;
                if (dataList.length > 0) {

                    for (let i = 0; i < dataList.length; i++) {

                        let temp = "";
                        let officialType = dataList[i].officialType
                        let officialTypeName = ''
                        switch (officialType) {
                            case "ADD_SCENE_OTHERS":
                                officialTypeName = '其他'
                                break;
                            case 'ADD_SCENE_PAID':
                                officialTypeName = '付费'
                                break;
                            case 'ADD_SCENE_PROFILE_CARD':
                                officialTypeName = '个人资料卡'
                                break;
                            case 'ADD_SCENE_PROFILE_LINK':
                                officialTypeName = '链接'
                                break;
                            case 'ADD_SCENE_QR_CODE':
                                officialTypeName = '二维码'
                                break;
                            case 'ADD_SCENE_SEARCH':
                                officialTypeName = '分享'
                                break;
                            case 'ADD_SCENE_WECHAT_ADVERTISEMENT':
                                officialTypeName = '广告'
                                break;
                            default:
                                officialTypeName = '无'
                                break;
                        }
                        // let firstJoinType = dataList[i].firstJoinType
                        // let currentType = sceneList.find(v=>v.id==firstJoinType)
                        // firstJoinTypeValue = currentType?currentType.remark:''
                        if (dataList[i].effective > 0) {
                            temp = '<span>是</span><br/><a href="AddUser.html?openid=' + dataList[i].openid + '" style="color: #337ab7">此用户订单</a>';
                        } else {
                            temp = '<span>否</span>';
                        }
                        dataHtml += '<tr>' +
                            '<td><input type="checkbox"  name="box" class="aceChild" data-id="' + dataList[i].openid + '"/></td>' +
                            '<td align="center"><img src="' + dataList[i].headimg + '" height="30" style="border-radius:50%"></td>' +
                            '<td align="center">' + (!isNotNull(dataList[i].nickname) ? "" : dataList[i].nickname) + '</td>' +
                            '<td align="center">' + (!isNotNull(dataList[i].phone) ? "无" : dataList[i].phone) + '</td>' +
                            '<td align="center">' + (!isNotNull(dataList[i].username) ? "" : dataList[i].username) + '</td>' +
                            '<td align="center">' + (dataList[i].sex == 0 ? "女" : "男") + '</td>' +
                            `<td align="center">${dataList[i].vipIntegralNum}<i onclick="handleEditPoints('${dataList[i].openid}','${dataList[i].vipIntegralNum}')" class="layui-icon layui-icon-edit" style="font-size: 20px; color: #1E9FFF;margin-left:10px"></i></td>` +
                            // '<td align="center">' + dataList[i].goldnum + '</td>' +
                            `<td align="center">${officialTypeName}</td>` +
                            `<td align="center">${dataList[i].officialState ? '已订阅' : '未订阅'}</td>` +
                            `<td align="center">${dataList[i].officialSubscribeTime || '无'}</td>` +//关注时间
                            `<td align="center">${dataList[i].officialUnsubscribeTime || '无'}</td>` +//取关时间
                            `<td align="center">${dataList[i].goinScenesReamrk || '无'}</td>` +//渠道来源
                            '<td align="center">' + dataList[i].intime_his + '</td>' +
                            `<td align="center">${dataList[i].recentJoinTime || ''}</td>` +
                            `<td align="center">${dataList[i].createOrderTime || ''}</td>` +//成单时间
                            '<td align="center">' + temp + '</td>' +
                            '<td align="center">' +
                            '<a href="AddUser.html?openid=' + dataList[i].openid + '" >编辑</a>&nbsp;&nbsp;&nbsp;' +
                            '<a href="#" data-id="' + dataList[i].openid + '"  data-info="user/delete"  onclick="DeleteInfo(this)">删除</a>&nbsp;&nbsp;&nbsp;' +
                            '<a href="#" data-info="' + dataList[i].id + '" data-id="' + dataList[i].openid + '"  data-info="FindCouponListPcByDisplay"  onclick="FindCouponListPcByDisplay(this)">兑换券</a>' +
                            '</td>' +
                            '</tr>';
                    }
                } else {
                    totalRecords = 0;
                    dataHtml += '<tr>' +
                        '<td colspan="12" style="text-align:center;">暂无数据</td>' +
                        '</tr>';
                }
                $(".data_content").html(dataHtml);
                page();
            } else {
                totalRecords = 0;
                dataHtml += '<tr>' +
                    '<td colspan="12" style="text-align:center;">暂无数据</td>' +
                    '</tr>';
                $(".data_content").html(dataHtml);
                page();
            }

        }

    });

}

function FindCouponListPcByDisplay(obj) {
    layer.open({
        type: 1,
        area: ['80%', '40%'],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 80%;margin: 0 auto;">' +
            '        <table class="layui-hide" id="tableInfo" lay-filter="tableInfo"></table>' +
            '<script type="text/html" id="barDemo">\n' +
            '                            <a lay-event="edit"><i class="layui-icon red"\n' +
            '                                                   title="兑换">兑换</i></a>&nbsp;&nbsp;&nbsp;&nbsp;\n' +
            '                        </script>' +
            '</form>'
    });
    let UserOpenid = $(obj).data("id");
    FindCouponListPcByDisplayInit(UserOpenid);
}

function FindCouponListPcByDisplayInit(UserOpenid) {
    $.ajax({
        url: httpurl + "/FindCouponListPcByDisplay",
        cache: false,
        data: {
            "display": 0,
        },
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        success: function (data) {
            if (data.rtnCode == 200) {
                let dataInfo = [];
                if (data.rtnCode == 200) {
                    dataInfo = data.data;
                }
                table.render({
                    elem: '#tableInfo',
                    data: dataInfo,
                    id: "tableInfoId",
                    limit: dataInfo.length,
                    cols: [
                        [{ field: 'name', align: "center", title: '优惠券名称', sort: true }, {
                            field: 'fullmoney',
                            align: "center",
                            title: '面值',
                            sort: true,
                            templet: function (res) {
                                return '满' + res.fullmoney + "减" + res.val;
                            }
                        }, { field: 'starttime', align: "center", title: '开始时间', sort: true }, { field: 'endtime', align: "center", title: '结束时间', sort: true }, { field: 'del', align: "center", width: 100, title: '操作', templet: '#barDemo', unresize: true }]
                    ]
                });
                //监听工具条
                table.on('tool(tableInfo)', function (obj) {
                    var data = obj.data;
                    if (obj.event === 'edit') {
                        $.ajax({
                            type: "POST",
                            url: httpurl + "/insertChangeCouponRecord",
                            cache: false,
                            data: JSON.stringify({
                                "openid": UserOpenid,
                                "cpid": data.id,
                                "istype": 0,
                            }),
                            headers: {
                                "Access-Control-Allow-Origin": "*",
                                "Access-Control-Allow-Methods": "*",
                                "Access-Control-Allow-Headers": "Authorization",
                                "Authorization": GetTokenInfo()
                            },
                            contentType: 'application/json',
                            success: function (data) {
                                top.layer.closeAll();

                                if (data.rtnCode == 200) {
                                    layer.msg(data.msg);
                                    FindCouponListPcByDisplayInit();
                                } else {
                                    top.layer.closeAll();
                                    layer.msg(data.msg);
                                }
                            },
                            error: function (data) {
                                layer.msg("接口读取失败，请稍后再试!!");
                            }
                        });
                    }
                });
            }
        },
        error: function (data) {
            layer.msg("接口读取失败，请稍后再试!!");
        }
    });
}
//分页
function page() {
    laypage.render({
        elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
        ,
        count: totalRecords //数据总数，从服务端得到
        ,
        curr: pageNo //获取起始页 location.hash.replace('#!fenye=', '')
        ,
        hash: 'fenye' //自定义hash值
        ,
        layout: ['count', 'prev', 'page', 'next', 'skip'],
        jump: function (obj, first) {
            //首次不执行
            if (!first) {
                //console.log("当前页==="+obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                //console.log("每页显示条数==="+obj.limit); //得到每页显示的条数
                pageNo = obj.curr;

                inituserdata(obj.limit, obj.curr);
            }
        }
    });
}

function DeleteUserList() {
    top.layer.confirm('您确定要删除选中的用户帐号吗？', { title: '提示信息' }, function (index) {
        var aceChild = $(".aceChild");
        var str = "";
        //拼接所有的用户OpenId
        for (var i = 0; i < aceChild.length; i++) {
            if (aceChild[i].checked) {
                str += aceChild[i].value + ",";
            }
        }
        if (str == "") {
            layer.msg("请选择要删除的用户!!");
            return;
        }
        str = str.substring(0, str.length - 1);
        $.ajax({
            url: httpurl + "/deleteOrderById",
            cache: false,
            data: {
                "OpenidList": str,
            },
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            success: function (data) {
                console.log("=====" + JSON.stringify(data));
                if (data.rtnCode == 200) {
                    top.layer.closeAll();
                    layer.msg("删除成功!!");
                    inituserdata();
                }
            },
            error: function (data) {
                layer.msg("接口读取失败，请稍后再试!!");
            }
        });
        layer.close(index);
    });
}

function handleEditPoints(openid,oldPoints) {
    console.log(openid);
    $('#points').html(oldPoints)
    layer.open({
        type: 1,
        btn:'确认',
        content: $('#editPoints-box'),
        yes:function(index){
            let value = $('#editpoints').val()
            editPoints(openid,value,index)
        }
    })
}
function editPoints(openid,updateIntegralNum,index){
    $.ajax({
        url: httpurl + "/updateUserVipIntegralNumByAdmin",
        cache: false,
        type:'post',
        data: {
            "openid":openid,
            "updateIntegralNum":updateIntegralNum
        },
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        // contentType: 'application/json',
        success: function (res) {
            if (res.rtnCode == 200) {
                layer.close(index);
                layer.msg(res.msg);
                inituserdata();
            }
        },
        error: function (err) {
            layer.msg("接口读取失败，请稍后再试!!");
        }
    });
}